package com.bookmanger.server.controller;

import com.bookmanger.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${spring.file.upload-dir:uploads}")
    private String uploadDir;

    /**
     * 上传图书封面图片
     * @param file 图片文件
     * @return 上传结果，包含图片访问路径
     */
    @PostMapping("/uploadCover")
    public Result uploadCover(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            // 获取项目根路径
            String projectRoot = System.getProperty("user.dir");
            // 构建完整的上传目录路径
            String fullUploadDir = projectRoot + File.separator + uploadDir;
            
            // 创建上传目录
            File dir = new File(fullUploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + extension;
            Path filePath = Paths.get(fullUploadDir, fileName);

            // 保存文件
            Files.write(filePath, file.getBytes());

            // 返回固定的完整图片访问路径
            String imgUrl = "http://localhost:8081/uploads/" + fileName;
            
            log.info("文件上传成功: {}", filePath.toAbsolutePath());

            return Result.success("上传成功", imgUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }
}